import Link from "next/link"; import { BillingRefreshListener } from "@/components/billing-refresh-listener"; import { CopyButton } from "@/components/copy-button"; import { GatewayBindForm } from "@/components/gateway-bind-form"; import { type BillingCredits, type BillingInvoices, type BillingSubscription, PopiartApiError, getBillingCredits, getBillingInvoices, getBillingSubscription, getBudgetSummary, getBudgetUsage, getPopiartEndpoint, getProjects, getSkillsCatalog, getViewerSession, } from "@/lib/popiart-api"; import { getLiveCopy } from "@/lib/live-copy"; import { type Locale } from "@/lib/site-content"; export const dynamic = "force-dynamic"; function formatNumber(locale: Locale, value: number) { return new Intl.NumberFormat(locale === "zh" ? "zh-CN" : "en-US").format(value); } function maskSecret(value?: string) { if (!value) { return "Unavailable"; } if (value.length <= 10) { return value; } return `${value.slice(0, 8)} • • • • ${value.slice(-4)}`; } function formatError(error: unknown) { if (error instanceof PopiartApiError) { return error.message; } if (error instanceof Error) { return error.message; } return String(error); } function coerceEpoch(value: unknown) { const num = Number(value); return Number.isFinite(num) && num > 0 ? num : 0; } function extractRecentOrder(invoices: BillingInvoices | null) { type BillingOrderItem = Record & { __kind: "subscription" | "points" }; const items: BillingOrderItem[] = [ ...((invoices?.subscription_orders?.items || []).map((item) => ({ ...item, __kind: "subscription" as const }))), ...((invoices?.point_orders?.items || []).map((item) => ({ ...item, __kind: "points" as const }))), ]; items.sort((a, b) => { const aTime = coerceEpoch(a.complete_time) || coerceEpoch(a.create_time) || Number(a.id || 0); const bTime = coerceEpoch(b.complete_time) || coerceEpoch(b.create_time) || Number(b.id || 0); return bTime - aTime; }); return items[0] ?? null; } export default async function ConsolePage({ params, }: { params: Promise<{ locale: string }>; }) { const { locale } = await params; const typedLocale = locale as Locale; const liveCopy = getLiveCopy(typedLocale); const session = await getViewerSession(); const isZh = typedLocale === "zh"; const pageTitle = isZh ? "控制台" : "Console"; const pageSubtitle = isZh ? "管理产品层密钥、查看用量、快速接入 CLI" : "Manage product-layer keys, usage, and quick CLI onboarding."; const remainingLabel = isZh ? "剩余 Credit" : "Remaining credits"; const remainingHint = isZh ? "总计可用额度" : "Total available quota"; const usedLabel = isZh ? "已使用" : "Used"; const usedHint = isZh ? "本月累计消耗" : "Consumed this month"; const callsLabel = isZh ? "调用次数" : "API calls"; const callsHint = isZh ? "本月 CLI / API 调用" : "CLI / API calls this month"; const projectsLabel = isZh ? "活跃项目" : "Projects"; const projectsHint = isZh ? "当前账号下可见项目" : "Projects visible to this account"; const keysTitle = isZh ? "API 密钥" : "API keys"; const quickTitle = isZh ? "快速安装指令" : "Quick install commands"; const quickBody = isZh ? "把下面这段命令复制到终端,完成 CLI 安装、登录和验证。" : "Copy these commands into your terminal to install the CLI, sign in, and verify the workflow."; const usageTitle = isZh ? "近期用量" : "Recent usage"; const usageEmpty = isZh ? "当前周期还没有技能用量。" : "No usage has been recorded for the current period."; const skillsTitle = isZh ? "官方技能" : "Official skills"; const skillsEmpty = isZh ? "当前账号下没有可见技能。" : "No skills are visible for this account yet."; const projectsTitle = isZh ? "项目" : "Projects"; const projectsEmpty = isZh ? "当前账号下没有可见项目。" : "No projects are visible for this account yet."; const billingTitle = isZh ? "网关账单" : "Gateway billing"; const billingStatusTitle = isZh ? "订阅状态" : "Subscription"; const billingCreditsTitle = isZh ? "积分余额" : "Credits"; const recentOrderTitle = isZh ? "最近订单" : "Recent order"; const recentOrderEmpty = isZh ? "当前还没有账单订单记录。" : "No billing orders yet."; const billingUnbound = isZh ? "当前 session 还没有绑定网关用户态,先绑定后才能读取真实订阅与积分。" : "This session is not bound to a gateway user yet. Bind it first to read live subscription and credit data."; const billingEmpty = isZh ? "当前没有有效订阅。" : "No active subscription was returned."; const walletEmpty = isZh ? "当前没有积分钱包记录。" : "No point wallets were returned."; const boundLabel = isZh ? "已绑定网关用户" : "Gateway user bound"; const preferenceLabel = isZh ? "扣费偏好" : "Billing preference"; const activeSubscriptionLabel = isZh ? "有效订阅" : "Active subscriptions"; const creditBalanceLabel = isZh ? "当前余额" : "Balance"; const walletCountLabel = isZh ? "钱包数量" : "Wallets"; const availablePointsLabel = isZh ? "可用积分" : "Available points"; const totalPointsLabel = isZh ? "总积分" : "Total points"; const walletSourceLabel = isZh ? "来源" : "Source"; const routeKeyLabel = isZh ? "路由键" : "Route key"; const usageJobsLabel = isZh ? "调用次数" : "Jobs"; const usageTokensLabel = isZh ? "Tokens" : "Tokens"; const usageCostLabel = isZh ? "费用" : "Cost"; const sessionKeyLabel = "POPIART_SESSION_KEY"; const endpointLabel = "POPIART_ENDPOINT"; const copyLabel = isZh ? "复制" : "Copy"; const copiedLabel = isZh ? "已复制" : "Copied"; const loginCta = isZh ? "去登录" : "Sign in"; const docsCta = isZh ? "查看文档" : "Open docs"; const bindLabels = { title: isZh ? "绑定网关用户" : "Bind gateway user", body: isZh ? "输入网关真实用户 ID 和 user access_token,当前 session 才能读取订阅、积分包和订单。" : "Enter the real gateway user ID and user access token so this session can read subscriptions, point packs, and orders.", userIdLabel: isZh ? "网关用户 ID" : "Gateway user ID", userIdHint: isZh ? "值必须等于网关当前登录用户的真实 ID。" : "This must match the real ID of the gateway user.", tokenLabel: isZh ? "网关 access_token" : "Gateway access token", tokenHint: isZh ? "使用网关 `/api/user/token` 生成的普通用户 access_token,不是渠道 key。" : "Use the user access token generated by gateway `/api/user/token`, not a channel key.", submit: isZh ? "绑定网关账单" : "Bind gateway billing", submitting: isZh ? "绑定中..." : "Binding...", invalidUserId: isZh ? "请输入有效的网关用户 ID。" : "Enter a valid gateway user ID.", invalidToken: isZh ? "请输入有效的网关 access_token。" : "Enter a valid gateway access token.", success: isZh ? "绑定成功,正在刷新账单数据。" : "Binding succeeded. Refreshing billing data.", }; if (!session) { return (

{pageTitle}

{pageSubtitle}

{liveCopy.console.unauthenticatedTitle}

{liveCopy.console.unauthenticatedBody}

{loginCta} {docsCta}
); } const [budgetResult, usageResult, skillsResult, projectsResult] = await Promise.allSettled([ getBudgetSummary(), getBudgetUsage(), getSkillsCatalog(), getProjects(), ]); const budget = budgetResult.status === "fulfilled" ? budgetResult.value : null; const usage = usageResult.status === "fulfilled" ? usageResult.value : null; const skills = skillsResult.status === "fulfilled" ? skillsResult.value : null; const projects = projectsResult.status === "fulfilled" ? projectsResult.value : null; const loadErrors = [budgetResult, usageResult, skillsResult, projectsResult] .filter((result) => result.status === "rejected") .map((result) => formatError((result as PromiseRejectedResult).reason)); let billingSubscription: BillingSubscription | null = null; let billingCredits: BillingCredits | null = null; let billingInvoices: BillingInvoices | null = null; const billingErrors: string[] = []; if (session.gateway_bound) { const [subscriptionResult, creditsResult, invoicesResult] = await Promise.allSettled([ getBillingSubscription(), getBillingCredits(), getBillingInvoices({ page: 1, pageSize: 1 }), ]); if (subscriptionResult.status === "fulfilled") { billingSubscription = subscriptionResult.value; } else { billingErrors.push(formatError(subscriptionResult.reason)); } if (creditsResult.status === "fulfilled") { billingCredits = creditsResult.value; } else { billingErrors.push(formatError(creditsResult.reason)); } if (invoicesResult.status === "fulfilled") { billingInvoices = invoicesResult.value; } else { billingErrors.push(formatError(invoicesResult.reason)); } } const recentOrder = extractRecentOrder(billingInvoices); const metrics = [ { label: remainingLabel, value: budget ? formatNumber(typedLocale, budget.remaining.tokens) : "--", hint: remainingHint, }, { label: usedLabel, value: budget ? formatNumber(typedLocale, budget.used.tokens) : "--", hint: usedHint, }, { label: callsLabel, value: usage ? formatNumber(typedLocale, usage.total.job_count) : "--", hint: callsHint, }, { label: projectsLabel, value: projects ? formatNumber(typedLocale, projects.total) : "--", hint: projectsHint, }, ]; const quickStart = [ "brew tap wtgoku-create/popi", "brew install wtgoku-create/popi/popiart", `export POPIART_ENDPOINT=${getPopiartEndpoint()}`, "popiart auth login --key ", "popiart skills list", ].join("\n"); return (

{pageTitle}

{pageSubtitle}

{loadErrors.length > 0 ? (
{liveCopy.console.loadErrorPrefix} {loadErrors.join(" | ")}
) : null}
{metrics.map((metric) => (
{metric.label} {metric.value} {metric.hint}
))}

{keysTitle}

{sessionKeyLabel} {maskSecret(session.session_key)}
{session.session_key ? ( ) : null}
{endpointLabel} {getPopiartEndpoint()}
{!session.gateway_bound ? ( ) : ( <>

{billingTitle}

{boundLabel}: {session.gateway_user_id}

{isZh ? "查看账单中心" : "Open billing"}
{billingErrors.length > 0 ? (
{billingErrors.join(" | ")}
) : null}

{billingStatusTitle}

{billingSubscription && billingSubscription.subscriptions.length > 0 ? (
{preferenceLabel} {billingSubscription.billing_preference || "-"}
{activeSubscriptionLabel} {formatNumber(typedLocale, billingSubscription.subscriptions.length)}
{billingSubscription.subscriptions.map((item, index) => (
{item.subscription?.member_level || "subscription"} {item.subscription?.status || "-"}
{availablePointsLabel} {formatNumber( typedLocale, billingSubscription.subscription_points[String(item.subscription?.id)]?.available_points || 0, )}
))}
) : (

{billingEmpty}

)}

{billingCreditsTitle}

{billingCredits ? (
{creditBalanceLabel} {formatNumber(typedLocale, billingCredits.balance)}
{walletCountLabel} {formatNumber(typedLocale, billingCredits.wallets.length)}
{billingCredits.wallets.slice(0, 4).map((wallet) => (
{walletSourceLabel}: {wallet.source_type} {availablePointsLabel}: {formatNumber(typedLocale, wallet.points)}
{totalPointsLabel} {formatNumber(typedLocale, wallet.points_total)}
))}
) : (

{walletEmpty}

)}

{recentOrderTitle}

{recentOrder ? (
{String(recentOrder.plan_title || recentOrder.package_name || recentOrder.trade_no || "order")} {String(recentOrder.status || "-")}
{String(recentOrder.money || "-")} {String(recentOrder.currency || "")} {String(recentOrder.payment_method || "-")}
{isZh ? "交易号" : "Trade no"} {String(recentOrder.trade_no || "-")}
{isZh ? "订单类型" : "Order kind"} {recentOrder.__kind === "subscription" ? (isZh ? "订阅订单" : "Subscription") : (isZh ? "积分包订单" : "Points pack")}
) : (

{recentOrderEmpty}

)}
)}

{quickTitle}

{quickBody}

            {quickStart}
          

{usageTitle}

{usage && usage.rows.length > 0 ? (
{usage.rows.map((row) => (
{row.dimension} {usageJobsLabel}: {formatNumber(typedLocale, row.job_count)}
{usageTokensLabel}: {formatNumber(typedLocale, row.tokens_used)} {usageCostLabel}: ${row.cost_usd.toFixed(2)}
))}
) : (

{usageEmpty}

)}

{skillsTitle}

{skills && skills.items.length > 0 ? (
{skills.items.slice(0, 6).map((skill) => (
{skill.name} {skill.description}
{skill.version} {routeKeyLabel}: {skill.route_key || skill.id}
))}
) : (

{skillsEmpty}

)}

{projectsTitle}

{projects && projects.items.length > 0 ? (
{projects.items.map((project) => (
{project.name} {project.id}
))}
) : (

{projectsEmpty}

)}
); }